<?php

class Session
{
    
    public static function start()
    {
        session_start();
    }
    
    public static function authenticate($username, $password)
    {
        $delegate = Page::getDelegate();
        if ($delegate->authenticate($username, $password))
        {
            Session::setAttribute('authenticated', true);
            if (USE_LOGIN_COOKIES === true)
            {
                Session::setCookieAttribute('username', $username);
                Session::setCookieAttribute('password', $password);
            }
            return true;
        }
        return false;
    }
    
    public static function authenticateByCookies($cookieUsernameVar = 'username', $cookiePasswordVar = 'password')
    {
        // Obtain username and encoded password from cookies
        $username = Session::getCookieAttribute($cookieUsernameVar);
        $password = Session::getCookieAttribute($cookiePasswordVar);
        
        Session::authenticate($username, $password);
    }
    
    public static function authenticated()
    {
        return (Session::getAttribute('authenticated') === true);
    }
    
    public static function getAttribute($attName)
    {
        if (isSet($_SESSION[$attName]))
            return $_SESSION[$attName];
        else
            return null;
    }
    
    public static function setAttribute($attName, $attValue)
    {
        $_SESSION[$attName] = $attValue;
    }
    
    public static function getCookieAttribute($attName)
    {
        if (isSet($_COOKIE[$attName]))
            return $_COOKIE[$attName];
        else
            return null;
    }
    
    public static function setCookieAttribute($attName, $attValue, $expireDays = 30)
    {
        setcookie($attName, $attValue, time() + 60*60*24 * $expireDays, "/");
    }
    
    public static function cleanCookieAttribute($attName)
    {
        // This is the preferred way to clear cookie values
        setcookie($attName, '', 1, "/");
    }
    
    public static function clean($reload = true)
    {
        session_unset();
        Session::setAttribute('authenticated', false);
        
        if (USE_LOGIN_COOKIES === true)
        {
            Session::cleanCookieAttribute('username');
            Session::cleanCookieAttribute('password');
        }
        
        // It is recommended to reload the page when changing access rights
        // to avoid bypassing some security checks.
        if ($reload === true) Controller::reload();
    }
    
}

?>